<template>
  <el-dialog
    draggable
    overflow
    v-model="visible"
    :title="titleMap[mode]"
    :width="1024"
    destroy-on-close
    @closed="$emit('closed')"
  >
    <sc-water-mark ref="wm" text="已记账" :color="'rgba(128,128,128,0.1)'">
      <el-form
        :model="form"
        :rules="rules"
        ref="dialogForm1"
        label-width="70px"
        label-position="top"
        class="formhead"
      >
        <el-row style="display: flex; align-items: center">
          <el-col :span="18" :column="4">
            <span style="font-size: 25px">{{ titleOrder }}</span>
            <span style="color: red; padding-left: 10px">{{ order_code_string }}</span>
          </el-col>
          <el-col :span="6">
            <el-descriptions direction="vertical">
              <el-descriptions-item
                label="编号"
                label-align="center"
                align="center"
                label-class-name="light-blue"
              >
                <el-input v-model="form.code" disabled placeholder="自动生成"></el-input
              ></el-descriptions-item>
              <el-descriptions-item
                label="单据日期"
                label-align="center"
                align="center"
                label-class-name="light-blue"
              >
                <el-date-picker
                  v-model="form.billdate"
                  type="date"
                  placeholder="选择日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-descriptions-item>
            </el-descriptions>
          </el-col>
        </el-row>
      </el-form>
      <!-- <sc-water-mark ref="wm" text="已审核" subtext="誉卓纱线"> -->
      <sk-tabs type="border-card">
        <el-tab-pane ref="tab" label="基础信息">
          <el-form
            :model="form"
            :rules="rules"
            ref="dialogForm"
            label-width="70px"
            label-position="right"
          >
            <el-row>
              <el-col :span="13">
                <el-row>
                  <el-col :span="8" align="客户">
                    <el-form-item label="客户" prop="customer_id">
                      <skAutoChoose
                        :disabled="form.iscustomer == 1"
                        v-model="form.customer.name"
                        :params="[
                          {
                            name: {
                              type: 'nlr',
                              value: 'YZ',
                            },
                          },
                        ]"
                        :name="'customer'"
                        :assign="form"
                      >
                      </skAutoChoose>
                    </el-form-item>
                  </el-col>

                  <el-col :span="8">
                    <el-form-item label="业务员" prop="salesman_id">
                      <skAutoChoose
                        v-model="form.salesman.name"
                        :name="'user'"
                        :asKey="'salesman_id'"
                        :assign="form"
                      >
                      </skAutoChoose>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="是否含税" prop="tax_id">
                      <el-switch
                        v-model="form.tax_id"
                        :active-value="1"
                        :inactive-value="0"
                      ></el-switch>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-row>
                      <el-col :span="8">
                        <el-form-item label="派车单" prop="car_id">
                          <skAutoChoose
                            v-model="form.car.code"
                            :name="'car'"
                            :assign="form"
                          >
                          </skAutoChoose>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="运输商" prop="car.company_id">
                          <skAutoChoose
                            v-model="form.car.company.name"
                            :name="'factory'"
                            :asKey="'company_id'"
                            :assign="form.car"
                            :params="[{ category_id: 110 }]"
                          >
                          </skAutoChoose>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="运费" prop="car.amount">
                          <el-input v-model="form.car.amount" clearable></el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="备注" prop="remark">
                      <el-input v-model="form.remark" clearable></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>
              <el-col :span="11">
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="欠款" prop="code">
                      <el-input label="账户剩余" v-model="ARBalance" clearable></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="额度" prop="code">
                      <el-input
                        label="客户额度"
                        v-model="credit_limit"
                        clearable
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="卷装号" prop="reel_total">
                      <el-input v-model="form.reel_total" clearable></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </el-form>

          <sc-VxeTable
            ref="save"
            :gridEvts="gridEvts"
            :data="form.details"
            :gridOps="gridOps"
            :height="300"
            :tablecode="'market_retail_save_finance'"
          >
          </sc-VxeTable>
        </el-tab-pane>
        <el-tab-pane label="附件">
          <sk-upload
            v-model="form.attachments"
            :limit="10"
            draggable
            tip="单个文件不要超过10M,请上传图像格式文件"
          >
          </sk-upload>
        </el-tab-pane>
        <el-tab-pane label="额外费用">
          <sc-VxeTable
            ref="savecost"
            :gridEvts="gridEvts"
            :data="form.extra_cost_details"
            :tablecode="'extra_cost_details'"
          >
          </sc-VxeTable>
        </el-tab-pane>
      </sk-tabs>
    </sc-water-mark>
    <!-- </sc-water-mark> -->
    <template #footer>
      <el-button @click="visible = false">取 消</el-button>
      <el-button
        type="primary"
        v-if="form.status_id == 1"
        :loading="isSaveing"
        @click="submit(1)"
        >保存</el-button
      >
      <el-button
        type="primary"
        v-if="form.status_id == 1"
        :loading="isSaveing"
        @click="submit(2)"
        >审核</el-button
      >
    </template>
  </el-dialog>

  <pack v-if="dialog.pack" ref="packDialog" @closed="dialog.pack = false"></pack>
</template>

<script>
import skDicSelect from "@/components/skDicSelect";
import skAutoChoose from "@/components/skAutoChoose";
import skSelectGroup from "@/components/skSelectGroup";
import { ElMessageBox } from "element-plus";
import pack from "./pack";
import XEUtils from "xe-utils";
export default {
  emits: ["success", "closed"],
  components: {
    skAutoChoose,
    skDicSelect,
    skSelectGroup,
    pack,
  },
  data() {
    return {
      mode: "add",
      dialog: {},
      order_code: [],
      ARBalance: 0,
      titleOrder: "发货",
      credit_limit: 0,
      storage_params: {},
      gridEvts: {
        copy: ({ button }) => {
          this.$TOOL.objCopy(button.selectRecords).map(v => {
            v.id = "key_" + v.id;
            this.form.extra_cost_details.push(v);
          });
        },
        setPrice: () => {
          this.openPromptBox();
        },
      },
      titleMap: {
        add: "新增",
        edit: "编辑",
      },

      storage_ids: [],
      form: {
        id: "",
        car: { company: {} },
        carry: { company: {} },
        status_id: 0,
        tax_id: 1,
        customer_id: null,
        customer: { name: "" },
        extra_cost_details: [],
        salesman: { name: "" },
        collection: [],
        department_id: 0,
        billdate: XEUtils.toDateString(new Date(), "yyyy-MM-dd"),
        code: "",
        iscustomer: null,
        remark: "",
        details: [],
        extra_cost: 0,
        attachments: [],
      },
      addTemplate: {
        billdate: XEUtils.toDateString(new Date(), "yyyy-MM-dd"),
        state: 1,
        trade_id: 0,
      },
      rules: {
        billdate: { required: true, message: "请选择单据日期" },
        customer_id: { required: true, message: "请选择客户" },
      },
      SelectRev: null,
      visible: false,
      isSaveing: false,
      gridOps: {
        height: 300,
        columns: [
          {
            field: "auxiliary_quantity",
            event: {
              keyup: ({ row, params }) => {
                row["se_auxiliary_quantity"] = row["auxiliary_quantity"];
                params.$grid.updateFooter();
              },
            },
          },
          {
            field: "se_auxiliary_quantity",
            event: {
              keyup: ({ params }) => {
                params.$grid.updateFooter();
              },
            },
          },
          {
            field: "se_quantity",
            event: {
              keyup: ({ e, row, params }) => {
                let { $grid, _rowIndex, items, column } = params;
                row["amount"] = (row["se_quantity"] * row["price"]).toFixed(2);
                params.$grid.updateFooter();
                this.enterAndSelect(e, _rowIndex, items, column, $grid);
              },
            },
          },
          {
            field: "price",
            event: {
              keyup: ({ e, row, params }) => {
                let { $grid, _rowIndex, items, column } = params;
                row["amount"] = (row["se_quantity"] * row["price"]).toFixed(2);
                params.$grid.updateFooter();
                this.enterAndSelect(e, _rowIndex, items, column, $grid);
              },
            },
          },
          {
            field: "amount",
            event: {
              keyup: ({ row, params }) => {
                row["price"] = (row["se_quantity"] * row["price"]).toFixed(2);
                params.$grid.updateFooter();
              },
            },
          },
        ],
      },
    };
  },
  mounted() {},

  computed: {
    order_code_string() {
      return this.order_code.toString();
    },
  },
  watch: {
    "form.details": {
      handler(val) {
        val.filter(v => this.computeQuantity(v));
      },
      deep: true,
    },
    "form.extra_cost_details": {
      handler(val) {
        this.form.extra_cost = val.reduce((sum, v) => sum + parseFloat(v.amount), 0);
      },
      deep: true,
    },
  },
  methods: {
    openPromptBox() {
      // 使用ElMessageBox.prompt方法创建弹框
      ElMessageBox.prompt("请输入单价", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /\S+/, // 输入框正则验证，不能为空
        inputErrorMessage: "内容不能为空",
      })
        .then(({ value }) => {
          // value是用户输入的内容
          this.form.details.filter(v => {
            v.price = value;
          });
        })
        .catch(() => {
          // 用户取消或关闭弹框
          console.log("取消输入");
        });
    },
    enterAndSelect(e, _rowIndex, items, column, $grid) {
      if (e.keyCode == 13) {
        if (_rowIndex == items.length - 1) {
          return;
        }

        $grid.setEditCell(this.form.details[_rowIndex + 1], column.property).then(() => {
          var ele = document.getElementsByClassName("is-focus");
          if (ele.length > 0) ele[0].getElementsByTagName("input")[0].select();
        });
        $grid.refreshScroll();
        $grid.scrollToRow(this.form.details[_rowIndex + 1]);
      }
    },
    computeQuantity(deltail) {
      let m_quantity = 0,
        mi_quantity = 0,
        amount = 0;

      if (deltail.unit_id == 2) {
        m_quantity += deltail.se_quantity;
        mi_quantity += parseFloat(deltail.se_quantity) * 0.9144;
      } else {
        m_quantity += parseFloat(deltail.se_quantity) * 1.09361;
        mi_quantity += parseFloat(deltail.se_quantity);
      }
      if (deltail.mi_quantity != mi_quantity) {
        deltail.mi_quantity = parseFloat(mi_quantity.toFixed(2));
      }
      if (deltail.m_quantity != m_quantity) {
        deltail.m_quantity = m_quantity;
      }
      amount = parseFloat((deltail.mi_quantity * deltail.price).toFixed(2));
      if (amount != parseFloat(deltail.amount)) {
        deltail.amount = amount;
      }
    },
    //显示
    open(mode = "add") {
      this.mode = mode;

      this.visible = true;
      this.$nextTick(() => {
        if (this.form.status_id == 2) {
          this.$refs.wm.create();
        } else {
          this.$refs.wm.clear();
        }
      });
      return this;
    },

    //表单提交方法
    submit(flage) {
      this.$refs.dialogForm1.validate(valid => {
        if (valid)
          this.$refs.dialogForm.validate(async valid => {
            if (valid) {
              this.isSaveing = true;
              this.form.flage = flage;
              var res = await this.$API.market.delivery.saveAndFinace.post(this.form);
              this.isSaveing = false;
              if (res.code == 200) {
                this.$emit("success", this.form, this.mode);
                this.visible = false;
                this.$message.success("操作成功");
              }
            }
          });
      });
    },
    async getItems(code) {
      var res = await this.$API.market.delivery.info.get({
        filter: [{ code: code }],
      });
      if (res.code == 200) {
        Object.assign(this.form, this.$TOOL.removeNull(res.data));
      }
    },

    //表单注入数据
    async setData(data) {
      await this.getItems(data.code);
    },
  },
};
</script>

<style>
.addicon .el-select {
  width: calc(100% - 24px);
}

.addicon .el-input__wrapper {
  border-top-right-radius: 0px;
  border-bottom-right-radius: 0px;
}

.addicon .el-button--small {
  border-top-left-radius: 0px;
  border-bottom-left-radius: 0px;
}
</style>
